package csc.daonjpa.java.controller;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import csc.daonjpa.java.dao.TransactionDAO;
import csc.daonjpa.java.domain.TargetAccount;
import csc.daonjpa.java.domain.Transaction;

@Controller
public class TransactionController {
	@RequestMapping(value="/createTransaction")
	public String addTransaction(HttpServletRequest request, Model model){
		String sourceAccount,targetAccount, targetBank, targetBranch;
		//obtains Entity Manager
		EntityManager entityManager = EntityManagerFactoryUtil.createEntityManager();
		targetAccount = (String) request.getParameter("selectedTargetAccount");
		if(targetAccount != "0"){
			TargetAccount targetAccountObject = entityManager.find(TargetAccount.class,targetAccount);
			targetBank = targetAccountObject.getBank();
			targetBranch = targetAccountObject.getBranch();
		}else{
			targetAccount = (String) request.getParameter("targetAccount");
			targetBank = (String) request.getParameter("targetBank");
			targetBranch = (String) request.getParameter("targetBranch");
		}
		
		sourceAccount = (String) request.getParameter("sourceAccount");
		
		double amount = Double.parseDouble( (String) request.getParameter("amount"));
		Date now = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
		String date = sdf.format(now);
		Transaction transaction = new Transaction(sourceAccount,targetAccount,targetBank,targetBranch,amount,date);
		TransactionDAO transactionDAO = new TransactionDAO();
		transactionDAO.addTransaction(transaction);
		return "forward:/loadTransaction.html";
	}
}
